package com.gla.giliair.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.gla.giliair.config.AlipayConfig;
import com.gla.giliair.dao.MOrderDao;
import com.gla.giliair.entity.MOrder;
import com.gla.giliair.service.AlipayService;
import com.gla.giliair.service.OrderService;
import com.gla.giliair.util.MapGenerator;
import com.gla.giliair.util.SnowflakeIdUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;

/**
 * @Description:
 * @Author: Yingtian qian
 * @Date: 2021/8/25 18:48
 */
@Service
public class AlipayServiceImpl implements AlipayService {
    @Autowired
    private MOrderDao mOrderDao;

    @Autowired
    private OrderService orderService;

    //获得初始化的AlipayClient
    private AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

    @Override
    public String aliPay(MOrder mOrder) {

        MOrder mOrderFromDB = orderService.selectOrderById(mOrder.getOrderId());

        if (mOrderFromDB == null) {
            return "{\n" +
                    "  \"msg\": \"订单不存在！\",\n" +
                    "  \"status\": 500\n" +
                    "}";
        }

        if (!mOrder.getCustomerId().equals(mOrderFromDB.getCustomerId())) {
            return "{\n" +
                    "  \"msg\": \"无权限支付！\",\n" +
                    "  \"status\": 501\n" +
                    "}";
        }

        if (mOrderFromDB.getOrderState() != 0) {
            return "{\n" +
                    "  \"msg\": \"订单状态不为待支付，不能支付！\",\n" +
                    "  \"status\": 502\n" +
                    "}";
        }

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = mOrderFromDB.getOrderNumber();
        //付款金额，必填
        String total_amount = String.valueOf(mOrderFromDB.getPrice());
        //订单名称，必填
        String subject = "飞不动（giliair）航空订票";
        //商品描述，可空
        String body = mOrderFromDB.getFlightNumber() + "航班支付";

        // 该笔订单允许的最晚付款时间，逾期将关闭交易。取值范围：1m～15d。m-分钟，h-小时，d-天，1c-当天（1c-当天的情况下，无论交易何时创建，都在0点关闭）。 该参数数值不接受小数点， 如 1.5h，可转换为 90m。
        String timeout_express = "1c";

        alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
                + "\"total_amount\":\"" + total_amount + "\","
                + "\"subject\":\"" + subject + "\","
                + "\"body\":\"" + body + "\","
                + "\"timeout_express\":\"" + timeout_express + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        //请求
        String result = null;
        try {
            result = alipayClient.pageExecute(alipayRequest).getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return result;
    }

    @Override
    public Map<String, Object> aliRefund(MOrder mOrder) {
        MOrder mOrderFromDB = orderService.selectOrderById(mOrder.getOrderId());
        if (mOrderFromDB == null) {
            return MapGenerator.getRes(500, "订单不存在！");
        }
        if (!mOrder.getCustomerId().equals(mOrderFromDB.getCustomerId())) {
            return MapGenerator.getRes(501, "无权限退票！");
        }
        if (mOrderFromDB.getOrderState() != 1) {
            if (mOrderFromDB.getOrderState() == 2) {
                return MapGenerator.getRes(503, "已选座，不能退票，请取消选座后重试！");
            }
            if (mOrderFromDB.getOrderState() == 3) {
                return MapGenerator.getRes(504, "已出票，不能退票！");
            }
            return MapGenerator.getRes(502, "订单状态不为已支付/未选座，不能退票！");
        }

        Date nowDate = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(nowDate);
        calendar.add(Calendar.HOUR, 1);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String sDateStr = sdf.format(calendar.getTime());
        try {
            Date sDate = sdf.parse(sDateStr);
            if (sDate.after(mOrderFromDB.getLeaveTime())) {
                return MapGenerator.getRes(512, "手动退款时间截止到起飞前一小时，已超时，请去机场人工办理手续！");
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }

        //订单状态设为-2(用户退票)
        mOrderFromDB.setOrderState(-2);
        if (mOrderDao.updateByPrimaryKeySelective(mOrderFromDB) > 0) {
            refund(mOrderFromDB.getOrderNumber(), String.valueOf(mOrderFromDB.getPrice()),"全额退款",true);
            return MapGenerator.getRes(200, "退票成功！");
        }
        return MapGenerator.getRes(520, "内部错误！");
    }

    public void refund(String orderNumber, String refundAmount, String reason, boolean isAll) {
        //设置请求参数
        AlipayTradeRefundRequest alipayRequest = new AlipayTradeRefundRequest();
        if (isAll) {
            alipayRequest.setBizContent("{\"out_trade_no\":\"" + orderNumber + "\","
                    + "\"refund_amount\":\"" + refundAmount + "\","
                    + "\"refund_reason\":\"" + reason + "\"}");
        } else {
            String out_request_no = String.valueOf(SnowflakeIdUtil.getSnowflakeId());
            alipayRequest.setBizContent("{\"out_trade_no\":\"" + orderNumber + "\","
                    + "\"out_request_no\":\"" + out_request_no + "\","
                    + "\"refund_amount\":\"" + refundAmount + "\","
                    + "\"refund_reason\":\"" + reason + "\"}");
        }
        AlipayTradeRefundResponse response = null;
        //请求
        try {
            response = alipayClient.execute(alipayRequest);
        } catch (AlipayApiException e) {

        }
    }
}
